//
//  CabinetCheckController.m
//  YunGui
//
//  Created by Hanen 3G 01 on 16/3/22.
//  Copyright © 2016年 hanen. All rights reserved.
//柜体验收

#import "CabinetCheckController.h"
#import "MJRefresh.h"
#import "CabinetCell.h"
#import "CabinetCheckDetailController.h"
#import "SideMenuUtil.h"
#import "NetModel.h"
#import "SettingButton.h"

#import "ShowPhotoViewController.h"

@interface CabinetCheckController()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    UITableView  *_tableView;
    
    
    UIView *_backView;
    UIView *_bottomPopView;
    SettingButton *_threeBtn;
    SettingButton *_fiveBtn;
    SettingButton *_lastBtn;
    
    UIButton *_cencelBtn;
    UIButton *righB;
    UIView   *_searchView;
    UITextField *_searchTF;
    
    int  pageNum;
    
    NSMutableArray *_dataArray;
//    UIButton *righB;
//    
//    UITextField *_searchTF;
//    UIView      *_searchView;
}

//- (void)sideLeftButton_selector:(id)sender;

@end

@implementation CabinetCheckController
@synthesize revealController;
- (void)viewDidLoad
{
    [super viewDidLoad];
    _dataArray = [NSMutableArray array];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
//    self.navigationItem.titleView = [ViewTool getNavigitionTitleLabel:@"柜体验收"];
    [ViewTool setNavigationBar:self.navigationController.navigationBar];
    self.navigationItem.title = @"柜体验收";
    
   [SideMenuUtil addViewGesture:self revealController:revealController];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.leftBarButtonItem=[ViewTool getListBarButtonItemWithTarget:self WithAction:@selector(sideLeftButton_selector:)];
//      self.navigationItem.leftBarButtonItem = [ViewTool getBarButtonItemWithTarget:self WithAction:@selector(sideLeftButton_selector:)];
    righB = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:20], [UIView getWidth:20])];
    [righB setBackgroundImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];
    [righB addTarget:self action:@selector(clickSearch:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barbtn = [[UIBarButtonItem alloc] initWithCustomView:righB];
    self.navigationItem.rightBarButtonItem = barbtn;
    
    [self addTableview];
    
    [self createSearchView];
//    [self addBottmView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDataa:) name:@"guiti" object:nil];
}

- (void)refreshDataa:(id)sender{
    [_tableView.mj_header beginRefreshing];
}
- (void)viewWillAppear:(BOOL)animated
{
    NSArray *controlleArr = self.navigationController.viewControllers;
    for (UIViewController *controll in controlleArr) {
        if ([controll isKindOfClass:[ShowPhotoViewController class]]) {
            [controll removeFromParentViewController];
        }
    }
}
- (void)viewDidAppear:(BOOL)animated{
    if (_isRefresh) {
        [_tableView.mj_header beginRefreshing];
    }
}
-(void)createSearchView
{
    CGFloat searchH = 60 +15;
    
    _searchView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, searchH)];
    _searchView.hidden = YES;
    [self.view addSubview:_searchView];
    
    UIView *searchV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
    [searchV setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"Btn_Normal_Sousuodi.png"]]];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10, self.view.width-40, searchV.height - 20)];
    imgView.image = [UIImage imageNamed:@"Btn_Normal_Sousuokuang.png"];
    [searchV addSubview:imgView];
    
    [_searchView addSubview:searchV];
    UIView *bg = [[UIView alloc]initWithFrame:CGRectMake(0, searchV.maxY, kScreenWidth, 15)];
    bg.backgroundColor = GrayBackColor;
    [_searchView addSubview:bg];
    
    UIView *line = [ViewTool getLineViewWith:CGRectMake(0, bg.maxY -1, kScreenWidth, 1) withBackgroudColor:UIColorFromRGB(0xe6e7eb)];
    [_searchView addSubview:line];
    
    _searchTF = [[UITextField alloc]initWithFrame:CGRectMake(imgView.x+10,imgView.y,imgView.width,imgView.height)];
    _searchTF.delegate = self;
    _searchTF.placeholder = @"网点编号/网点名称/小区名称";
    [_searchTF setValue:LEFTLINECOLOR forKeyPath:@"_placeholderLabel.textColor"];
    [_searchTF setValue:[UIFont systemFontOfSize:16.0f] forKeyPath:@"_placeholderLabel.font"];
    _searchTF.returnKeyType = UIReturnKeySearch;
    [searchV addSubview:_searchTF];
    
//    UIButton *searchImgBtn = [ViewTool getButtonImgWithTarget:self withFrame:CGRectMake(self.view.width / 2.0f - 10, imgView.y+(imgView.height-20)/2, 20, 20) WithString:@"Btn_Normal_Huisousuo" WithAction:@selector(hideSearchButton)];
//    [searchV addSubview:searchImgBtn];
    
}
- (void)hideSearchButton{
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
//    [_dataArray removeAllObjects];
//    [self loadCheckListDataWithSEarchText:textField.text];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [SVProgressHUD showWithStatus:@"搜索中"];
    [_dataArray removeAllObjects];
    pageNum = 1;
    [self loadCheckListDataWithSEarchText:textField.text];
    return YES;
}
#pragma mark --搜索框
- (void)clickSearch:(UIButton *)btn
{
    
    if (btn.selected == NO) {
        [UIView animateWithDuration:0.25 animations:^{
            _searchView.hidden = NO;
            _tableView.frame = CGRectMake(0, _searchView.height, kScreenWidth, kScreenHeight - 64 - _searchView.height);
        }];
        
    }else{
        [_searchTF resignFirstResponder];
        [UIView animateWithDuration:0.25 animations:^{
            _searchView.hidden = YES;
            _searchTF.text = @"";
            _tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 );
        }];
    }
    btn.selected = !btn.selected;
}

- (void)addTableview
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = GrayBackColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //        [weakSelf loadNewData];
        [self loadNewData];
    }];
    
    // 马上进入刷新状态
    [_tableView.mj_header beginRefreshing];
    
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //        [weakSelf loadMoreData];
        [self loadMoreData];
    }];
}
- (void)loadNewData
{
    [_dataArray removeAllObjects];
    pageNum = 1;
    [self loadCheckListDataWithSEarchText:_searchTF.text];
    
    //    [_tableView reloadData];
//    [_tableView.mj_header endRefreshing];
}
- (void)loadMoreData
{
    pageNum ++;
    [self loadCheckListDataWithSEarchText:_searchTF.text];
}
- (void)loadCheckListDataWithSEarchText:(NSString *)searchtext
{
    NSInteger str = [[NSUserDefaults standardUserDefaults] integerForKey:@"userId"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{@"method":@"app.branchCheck.list.page",@"page" :@(pageNum),@"user_id" :@(str),@"pageNum" : @(10)}];
    if (searchtext.length != 0 ) {
        [dict setObject:_searchTF.text forKey:@"search"];
    }
    //            [talkingArray removeAllObjects];
    NSDictionary *paramersDict = [DataTool addSignToDic:dict];
    NSLog(@"柜体列表参数%@",paramersDict);
    [DataTool postWithUrl:HEAD_URL parameters:paramersDict success:^(id data) {
        [SVProgressHUD dismiss];
        id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"柜体的数据%@",backData);
        NSString *status = [(NSDictionary *)backData objectForKey:@"status"];
        if ([status isEqualToString:@"SUCCESS"]) {
            NSDictionary * dataDict = [DataTool changeType:[(NSDictionary *)backData objectForKey:@"data"]];
            NSArray *dataArray2 = dataDict[@"listData"];
            int total = [dataDict[@"total"] intValue];
            if (dataArray2.count == 0 && _dataArray.count == 0) {
                [Tools showMessage:@"没有数据,请搜索一下" view:self];
//                [_tableView.mj_header endRefreshing];
//                return ;
            }else if (total <= 10){
                [_tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                if (dataArray2.count < 10){
                    [_tableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [_tableView.mj_footer endRefreshing];
                }
            }
            for (int i = 0; i< dataArray2.count; i++) {
                NetModel *model = [[NetModel alloc] init];
                [model setValuesForKeysWithDictionary:dataArray2[i]];
                [_dataArray addObject:model];
            }
        }else{
            int code = [[(NSDictionary *)backData objectForKey:@"code"] intValue];
            NSString *msg = [(NSDictionary *)backData objectForKey:@"msg"];
            NSLog(@"柜体返回%@%d%@",status,code,msg);
            [Tools showMessage:msg view:self];
            if (code == 999991) {
                [_dataArray removeAllObjects];
                [_tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [_tableView.mj_footer endRefreshing];
            }
        }
        [_tableView reloadData];
        [_tableView.mj_header endRefreshing];
        
    } fail:^(NSError *error) {
        NSLog(@"柜体error:%@",error);
        [Tools showMessage:error.localizedDescription view:self];
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshingWithNoMoreData];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CabinetCell *cell = [CabinetCell cellWithTabelView:tableView];
    if(_dataArray.count  != 0 ){
    cell.model = _dataArray[indexPath.row];
    }
    return cell;

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [UIView animateWithDuration:0.25 animations:^{
//        _searchView.hidden = YES;
//        _tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64);
    }];
//     righB.selected = NO;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CabinetCheckDetailController *cabinetVC = [[CabinetCheckDetailController alloc] init];
    NetModel *model;
    if(_dataArray.count != 0 ){
        model = _dataArray[indexPath.row];
        
    }
    cabinetVC.branchId = model.branch_id;
    cabinetVC.isCheckOK = [model.status intValue] ==1 ? YES : NO;
    cabinetVC.staus = [model.status intValue];
    cabinetVC.isFirst = YES;
    [self.navigationController pushViewController:cabinetVC animated:YES];
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPat{
    
    return [CabinetCell cellHeight];
}

#pragma mark --点击左上角的按钮
- (void)sideLeftButton_selector:(id)sender {
    
    [self.revealController toggleSidebar:!self.revealController.sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
}

@end
